package com.steamedfish.auctionsecurityserveroauth2.service.impl;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.steamedfish.auctionsecurityserveroauth2.service.SendSMS;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Service
public class DefaultSendSMSImp implements SendSMS {

    @Autowired
    private Client aliSmsClient;

    @Autowired
    private SimpleMailMessage simpleMailMessage;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private MailSender mailSender;

    @Override
    public boolean send(String telephone,String code) {


        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setPhoneNumbers(telephone)
                .setSignName("矿小厨")
                .setTemplateCode("SMS_213771298")
                .setTemplateParam("{\"code\":\"" + code + "\"}");

        try {
            SendSmsResponse a = aliSmsClient.sendSms(sendSmsRequest);
            System.out.println(a.body.message);
            redisTemplate.opsForValue().set(telephone, code,5, TimeUnit.MINUTES);

        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

        return true;
    }

    @Override
    public boolean sendByMail(String mail, String code) {
        simpleMailMessage.setTo(mail);
        String codeText = "尊敬的" + mail + "用户，您好。您正在使用的验证码为：" + code + "。验证码有效时常5分钟，请妥善保管，不要泄露给任何人";
        simpleMailMessage.setText(codeText);

        try {
            mailSender.send(simpleMailMessage);
            redisTemplate.opsForValue().set(mail, code,5, TimeUnit.MINUTES);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("发送邮件失败");
        }
        return true;
    }
}